﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CreateItem : MonoBehaviour {

	public GameObject[] items; 

	public GameObject[] parentItems;

	public GameObject holder;

	public static CreateItem Instance;

	public int objCount = 0;

	public int totalGenerateCount = 90;

	public int deadIslandCount = 0;

	public float reGenerateTimeSeperate = 0.1f;
	float timeCount = 0;

	bool isInRegenerateTime = false;

	private void Awake() {
		Instance = this;
	}

	// Use this for initialization
	void Start () 
	{
		CreateRandomStart();
	}
	
	// Update is called once per frame
	void Update () 
	{
		CheckInput();

		CheckIsCountLowToGenerateItem();

		if(isInRegenerateTime)
		{
			timeCount += Time.deltaTime;
			if(timeCount >= reGenerateTimeSeperate)
			{
				isInRegenerateTime = false;
				timeCount = 0;
			}
		}
	}

	void CreateRandomStart()
	{
		for(int i = 0; i < 30; i++)
		{
			SoundManager.Instance.PlayFirstGenerateBallSound();
			RandomCreateOneDropItem();
			//int index = Random.Range(0, 2);

			//CreateDropItem(index, parentItems[index].transform.localPosition+ new Vector3(Random.Range(-10.0f, 10.0f), Random.Range(-10.0f, 10.0f) - 100, 0));
			//objCount ++;
		}
	}

	public void GenerateMiddleBall(int level)
	{
		//int index = Random.Range(0, 2);
		int index = 2;
		var newObj = CreateDropItem(index, parentItems[0].transform.localPosition + new Vector3(Random.Range(100.0f, 300.0f), Random.Range(-30.0f, 10.0f) + 0, 0));
		var levelObj = newObj.AddComponent<BallLevel>();
		levelObj.ballLevel = level;
		var ballDiffImage = newObj.GetComponent<BallDiffImage>();
		ballDiffImage.SetLevelAndRandomEmoji(level - 1);
		objCount ++;
	}

	void RandomCreateOneDropItem()
	{
		int index = Random.Range(0, 2);
		var newObj = CreateDropItem(index, parentItems[index].transform.localPosition + new Vector3(Random.Range(-10.0f, 30.0f), Random.Range(-30.0f, 10.0f) - 100, 0));
		var levelObj = newObj.AddComponent<BallLevel>();
		levelObj.ballLevel = 1;
		objCount ++;
	}

	GameObject CreateDropItem(int index, Vector3 position)
	{
		var newObj = GameObject.Instantiate(items[index]);

		newObj.transform.SetParent(transform);
		if(index != 2)
		{
			newObj.transform.localScale = Vector3.one;
		}
		else
		{
			newObj.transform.localScale = new Vector3(1.3f, 1.3f, 1.3f);
		}
		newObj.transform.localPosition = position;

		newObj.AddComponent<CheckDestroy>();

		return newObj;
	}

	void CheckIsCountLowToGenerateItem() //检查个数是否不够，从而继续生成物体
	{
		if(objCount < 20 && totalGenerateCount > 0)
		{
			if(!isInRegenerateTime)
			{
				RandomCreateOneDropItem();
				timeCount = 0;
				isInRegenerateTime = true;

				totalGenerateCount--;
			}
		}
	}

	void CheckInput()
	{

		#if UNITY_EDITOR
			if(Input.GetMouseButton(0))
			{
				holder.SetActive(false);
			}
			else
			{
				holder.SetActive(true);
			}
		#else
			if(Input.touchCount > 0)
			{
				holder.SetActive(false);
			}
			else
			{
				holder.SetActive(true);
			}
		#endif
	}
}
